<template>
  <el-dialog
    v-model="visible"
    :title="type === 'edit' ? '编辑' : '添加'"
    width="650px"
    @closed="onReset"
    append-to-body
  >
    <el-form :model="form" :rules="rules" inline label-width="65px" ref="formRef">
      <el-row>
        <el-form-item label="手机号" prop="blackPhone">
          <el-input
            style="width: 500px"
            v-model="form.blackPhone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            style="width: 500px"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
            clearable
          />
        </el-form-item>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineProps } from 'vue';
import { addBlackList, editBlackList } from '@/api/role';
const visible = ref(false);
const loading = ref(false);
const formRef = ref();
const resolveValue = ref();
const type = ref('add');
const props = defineProps({
  params: Object
});
onMounted(() => {
  console.log(props, 'props---');
});
const form = reactive({
  blackPhone: '',
  remark: ''
});
const rules = reactive({
  blackPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  remark: [{ required: false, message: '请输入备注', trigger: 'blur' }]
});

const confirm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      add();
    }
  });
};
const init = (data?: { type: string; row: object }) => {
  if (data) {
    type.value = data.type;
  }
  if (type.value === 'edit') {
    Object.assign(form, data?.row);
  }

  visible.value = true;
  return new Promise((resolve) => {
    resolveValue.value = resolve;
  });
};
const add = async () => {
  loading.value = true;
  if (type.value === 'edit') {
    editBlackList(form).then(() => {
      ElMessage.success('编辑成功');
      resolveValue.value();
      loading.value = false;
      visible.value = false;
    });
  } else {
    addBlackList(form).then(() => {
      ElMessage.success('添加成功');
      resolveValue.value();
      loading.value = false;
      visible.value = false;
    });
  }
};
const onReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};

defineExpose({ init });
</script>

<style lang="scss" scoped></style>
